/*
 * StoreReader.java
 *
 * Created on Sep 27, 2007, 10:46:54 PM
 *
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package passvault.resources;

/**
 *
 * @author patrick
 */
public class StoreReader {

    public String[] options = null;
    public String filename = null;
    public String fileformat = null;
    public String password = null;
    public boolean do_decrypt = false;

    public StoreReader(String[] in_options) {
        options = in_options;
        filename = options[0];
        fileformat = options[1];
        if (options.length > 2) { 
            password = options[2]; 
            do_decrypt = true;
        }
    }

    public boolean valid_data() {
        // Stub to validate data
        return true;
    }

    public PasswordStore read_store_data() {
        PasswordStore pws = new PasswordStore();
        String raw_input = read_file();
//        if (raw_input == null) { return pws; }
        if (options[1].equals("xml")) {
            if (! raw_input.startsWith("<?xml")) {
                if (do_decrypt) {
                    raw_input = decrypt_text(raw_input);
                }
            }
            pws = read_xml(raw_input);
        }
        return pws;
    }
    
    private String decrypt_text(String encrypted_text) {
        AES aes = new AES();
        aes.init(password);
        String decrypted_text = aes.decrypt(encrypted_text);
        return decrypted_text;
    }
    
    private String read_file() {
        String output = null;
        ReadFile file_reader = new ReadFile(filename);
        output = file_reader.read();
        return output;
    }
    
    private PasswordStore read_xml(String xml_input) {
        PasswordStore pws = null;
        if (xml_input != null ) {
            XMLReader xml = new XMLReader();
            pws = xml.read_xml(xml_input);
        }
        return pws;
    }
}